var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.STOCK24;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'stock/data/page_byshop';
var _height = $(parent).height()-328,_width = $(parent).width()-192;
var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:true,module:'stock'},
			width : 500,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				selectShops = selected;
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].sp_code);
					names.push(selected[i].sp_name);
				}
				$("#shopCodes").val(codes.join(","));
				$("#shop_name").val(names.join(","));
			},
			cancel:true
		});
	},
	doQueryBrand : function(){
		commonDia = $.dialog({
			title : '选择品牌',
			content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].bd_code);
					names.push(selected[i].bd_name);
				}
				$("#bd_code").val(codes.join(","));
				$("#bd_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 300,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].tp_code);
					names.push(selected[i].tp_name);
				}
				$("#tp_code").val(codes.join(","));
				$("#tp_name").val(names.join(","));
			},
			close:function(){
			},
			cancel:true
		});
	}
};

var allShops = [];
var selectShops = [];
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_type = $("#td_type").cssRadio({ callback: function($_obj){
			var type = $_obj.find("input").val();
			$("#type").val(type);
			THISPAGE.initGrid();
			switch(type){
				case 'brand' : 
					$('#grid').setLabel("code","品牌编号");
					$('#grid').setLabel("name","品牌名称");
					break ;
				case 'type' : 
					$('#grid').setLabel("code","类别编号");
					$('#grid').setLabel("name","类别名称");
					break ;
				default :
					break ;
			}	
			
		}});
		this.$_exactQuery = $("#exactQuery").cssCheckbox();
		this.getAllShop();
		this.initSeason();
		this.initYear();
	},
	initSeason:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"base/dict/list?dtl_upcode=KEY_SEASON",
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.data != "" && data.data.length > 0){
					var seasons = data.data;
					seasons.unshift({dtl_code:"",dtl_name:"全部"});
					$('#span_pd_season').combo({
						value : 'dtl_code',
						text : 'dtl_name',
						width : 207,
						listHeight : 300,
						listId : '',
						defaultSelected : 0,
						editable : false,
						callback : {
							onChange : function(data) {
								if(data.dtl_code != ""){
									$("#pd_season").val(data.dtl_name);
								}else{
									$("#pd_season").val("");
								}
							}
						}
					}).getCombo().loadData(seasons,["dtl_name",$("#pd_season").val(),0]);
				}
			}
		 });
	},
	initYear:function(){
		var currentYear = new Date().getFullYear();
		var data = [
		    {Code:"",Name:"全部"},
			{Code:""+parseInt(currentYear+1)+"",Name:""+parseInt(currentYear+1)+""},
			{Code:""+parseInt(currentYear)+"",Name:""+parseInt(currentYear)+""},
			{Code:""+parseInt(currentYear-1)+"",Name:""+parseInt(currentYear-1)+""},
			{Code:""+parseInt(currentYear-2)+"",Name:""+parseInt(currentYear-2)+""},
			{Code:""+parseInt(currentYear-3)+"",Name:""+parseInt(currentYear-3)+""},
			{Code:""+parseInt(currentYear-4)+"",Name:""+parseInt(currentYear-4)+""},
			{Code:""+parseInt(currentYear-5)+"",Name:""+parseInt(currentYear-5)+""}
		];
		$('#span_pd_year').combo({
			data:data,
			value: 'Code',
			text: 'Name',
			width :206,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#pd_year").val(data.Code);
				}
			}
		}).getCombo();
	},
	getAllShop:function(){/*获取所有店铺数据*/
		$.ajax({
			type:"POST",
			async:false,
			url:config.BASEPATH+"base/shop/up_sub_list?sidx=sp_code&sord=asc",
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					allShops=data.data;
				}
			}
		});
	},
	gridTotal:function(){
    	var grid = $('#grid');
		var footerData = {code:'合计'};
		
		if(selectShops != null && selectShops.length > 0){
			for (var i = 0; i < selectShops.length; i++) {
				footerData["amountMap."+selectShops[i].sp_code] = grid.getCol("amountMap."+selectShops[i].sp_code,false,'sum');
				footerData["moneyMap."+selectShops[i].sp_code] = grid.getCol("moneyMap."+selectShops[i].sp_code,false,'sum');
			}
		}else{
			for (var i = 0; i < allShops.length; i++) {
				footerData["amountMap."+allShops[i].sp_code] = grid.getCol("amountMap."+allShops[i].sp_code,false,'sum');
				footerData["moneyMap."+allShops[i].sp_code] = grid.getCol("moneyMap."+allShops[i].sp_code,false,'sum');
			}
		}
		footerData["totalamount"] = grid.getCol("totalamount",false,'sum');
		footerData["totalmoney"] = grid.getCol("totalmoney",false,'sum');
		grid.footerData('set',footerData);
    },
	initGrid:function(){
		$("#grid").jqGrid('GridUnload');
		var colModel = [
	    	{label:'品牌编号',name: 'code',index:'code',width:80},
	    	{label:'品牌名称',name: 'name',index:'name',width:100}
	    ];
		if(selectShops != null && selectShops.length > 0){
			for (var i = 0; i < selectShops.length; i++) {
				colModel.push({label:'数量',name: "amountMap."+selectShops[i].sp_code,index:'',width: 80,sortable:false,align:'right'});
				colModel.push({label:'金额',name: "moneyMap."+selectShops[i].sp_code,index:'',width: 80,sortable:false,align:'right',formatter: PriceLimit.formatByCost});
			}
		}else{
			for (var i = 0; i < allShops.length; i++) {
				colModel.push({label:'数量',name: "amountMap."+allShops[i].sp_code,index:'',width: 80, sortable:false,align:'right'});
				colModel.push({label:'金额',name: "moneyMap."+allShops[i].sp_code,index:'',width: 80, sortable:false,align:'right',formatter: PriceLimit.formatByCost});
			}
		}
		colModel = colModel.concat([
			{label:'数量',name: 'totalamount',index: 'totalamount',width:70,align:"right"},
			{label:'金额',name: 'totalmoney',index: 'totalmoney',width:70,align:"right",formatter: PriceLimit.formatByCost}
		]);
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'code'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
			},
			loadError: function(xhr, status, error){		
			}
	    });
		var groupHeaders = [];
		
		if(selectShops != null && selectShops.length > 0){
			for (var i = 0; i < selectShops.length; i++) {
				groupHeaders.push({startColumnName : 'amountMap.'+selectShops[i].sp_code,numberOfColumns : 2, titleText : selectShops[i].sp_name});
			}
		}else{
			for (var i = 0; i < allShops.length; i++) {
				groupHeaders.push({startColumnName : 'amountMap.'+allShops[i].sp_code,numberOfColumns : 2, titleText : allShops[i].sp_name});
			}
		}
		groupHeaders.push({startColumnName : 'totalamount',numberOfColumns : 2, titleText :'小计' });
        $("#grid").jqGrid('setGroupHeaders', { 
			useColSpanStyle : true, // 没有表头的列是否与表头列位置的空单元格合并 
			groupHeaders : groupHeaders
		});
	},
	buildParams : function(){
		var params = '';
		params += 'type='+$("#type").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&tp_code='+$("#tp_code").val();
		params += '&pd_season='+$("#pd_season").val();
		params += '&pd_year='+$("#pd_year").val();
		params += '&pd_no='+Public.encodeURI($("#pd_no").val());
		params += '&exactQuery='+(THISPAGE.$_exactQuery.chkVal().join()? 1 : 0);
		if(selectShops.length > 0){
			params += '&shopCodes='+$("#shopCodes").val();
		}else{
			var sp_code = [];
			for (var i = 0; i < allShops.length; i++) {
				sp_code.push(allShops[i].sp_code);
			}
			params += '&shopCodes='+sp_code.join(",");
		}
		return params;
	},
	reset:function(){
		$("#pd_no").val("");
		$("#bd_name").val("");
		$("#bd_code").val("");
		$("#tp_name").val("");
		$("#tp_code").val("");
		$("#span_pd_season").getCombo().selectByValue("");
		$("#span_pd_year").getCombo().selectByValue("");
		$("#shop_name").val("");
		$("#shopCodes").val("");
		selectShops = [];
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.initGrid();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.initGrid();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
	}
}
THISPAGE.init();